package com.example.mgsnew.Handler;


import com.alibaba.fastjson.JSONObject;
import com.example.common.domain.Messages.Mgs;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@ChannelHandler.Sharable
@Component
public class NotificationHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    // 存储在线学生的Channel，key为学生ID，value为Channel
    private final ConcurrentHashMap<String, Channel> studentChannels = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        // 处理客户端消息（如认证、心跳等）
        String request = msg.text();
        JSONObject json = JSONObject.parseObject(request);

        String action = json.getString("action");
        if ("auth".equals(action)) {
            String studentId = json.getString("studentId");
            if (studentId != null) {
                studentChannels.put(studentId, ctx.channel());
                System.out.println("学生 " + studentId + " 已连接");
            }
        }
    }

    // 发送通知给所有在线学生
    public void sendNotificationToAllStudents(Mgs mgs) throws JsonProcessingException {
        String json = objectMapper.writeValueAsString(mgs);
        System.out.println(mgs.getData());
        System.out.println("发送签到通知给所有在线学生:"+mgs.getCreate());
        studentChannels.forEach((studentId, channel) -> {
            if (channel.isActive()) {
                System.out.println("发送签到通知给学生 " + studentId);
                channel.writeAndFlush(new TextWebSocketFrame(json));
            }
        });
    }

    // 发送作业给所有在线学生
    public void sendHomework(Mgs mgs) throws JsonProcessingException {
        String json = objectMapper.writeValueAsString(mgs);
        System.out.println(mgs.getData());
        System.out.println("发送作业通知给所有在线学生");
        studentChannels.forEach((studentId, channel) -> {
            if (channel.isActive()) {
                System.out.println("发送作业通知给学生 " + studentId);
                channel.writeAndFlush(new TextWebSocketFrame(json));
            }
        });
    }


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("新连接: " + ctx.channel().id().asShortText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // 移除离线学生的Channel
        studentChannels.entrySet().removeIf(entry -> entry.getValue().id().equals(ctx.channel().id()));
        System.out.println("连接断开: " + ctx.channel().id().asShortText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
